﻿using System.IO;
using System.Text;

namespace Oxage.CNC.Models
{
	public class XamlPathDataCodeSerializer : IMachineCodeSerializer
	{
		#region Public methods
		public string Serialize(XamlPathDataCode code)
		{
			byte[] data = Serialize(code as IMachineCode);
			return Encoding.ASCII.GetString(data);
		}

		public XamlPathDataCode Deserialize(string code)
		{
			byte[] data = Encoding.ASCII.GetBytes(code);
			return Deserialize(data) as XamlPathDataCode;
		}
		#endregion

		#region IMachineCodeSerializer Members
		public byte[] Serialize(IMachineCode code)
		{
			//Block represents a single line in G code syntax
			var builder = new StringBuilder();
			foreach (var block in code.Blocks)
			{
				//Inline represents a particular command in a line
				var b = new StringBuilder();
				foreach (var inline in block.Inlines)
				{
					if (b.Length > 0)
					{
						b.Append(" ");
					}
					b.Append(inline.ToString());
				}
				builder.AppendLine(b.ToString());
			}
			string gcode = builder.ToString();
			return Encoding.ASCII.GetBytes(gcode);
		}

		public IMachineCode Deserialize(byte[] data)
		{
			var result = new XamlPathDataCode();

			string lines = Encoding.ASCII.GetString(data);
			var reader = new StringReader(lines);

			string line = null;
			while ((line = reader.ReadLine()) != null)
			{
				if (!string.IsNullOrEmpty(line) && line.Trim().Length > 0)
				{
					var block = new XamlPathDataCodeBlock(line);
					result.Blocks.Add(block);
				}
			}

			return result;
		}
		#endregion
	}
}
